let currentIframe = $(getIframeByElement(document.body));
let currentRoute = currentIframe.attr("src");
let baseInfo = getParamsObj(currentRoute);
let examineFilePath;
let productData=[];
//防止表头与表格不对齐
$(window).resize(function () {
    $("#productDetail").bootstrapTable('resetView');
    $("#exchangeProductDetail").bootstrapTable('resetView');
});
//将路由上的参数转为对象的形式
function getParamsObj(currentRoute){
    if(currentRoute.indexOf("?")){
        let paramsStr=currentRoute.substring(currentRoute.indexOf("?")+1);
        let paramsArr=paramsStr.split('&');
        let obj={};
        for(var i=0;i<paramsArr.length;i++){
            var paramItem=paramsArr[i];
            var key=paramItem.split('=')[0];
            var value=paramItem.split('=')[1]=='null'?'':paramItem.split('=')[1];
            obj[key]=value;
        }
        return obj

    }else{
        return {};
    }
}
function baseInfoAssignment(data){
    examineFilePath = baseInfo.accessUrl;
    $("#orderNumberText").text(baseInfo.orderNumber);
    $("#applyRemark").text(baseInfo.remarks);
    //基本信息赋值 赋值节点的id和数据中的key一致
    let demos=$(".contractTypeContainer>.form-group");
    for(let i=0;i<demos.length;i++){
        var id=demos.eq(i).find("span").attr('id');
        if(id=='productStatus'){
            let productStatus='';
             switch(data[id]){
                 case '0':
                     productStatus='回款';
                     break;
                 case '1':
                     productStatus='退款';
                     break;
                 case '2':
                     productStatus='部分回款';
                     break;
                 case '3':
                     productStatus='已回款';
                     break;
                 case '4':
                     productStatus='作废';
                     break;
                 case '5':
                     productStatus='已兑换';
                     break;

             }
            demos.eq(i).find("span").text(productStatus)
        }else{
            demos.eq(i).find("span").text(data[id])
        }
    }
    getApprovalStatus()
}
function getApprovalStatus(){
    $.ajax({
        url: '/csd/productManager/selectApprovedform',
        type: 'POST',
        dataType: "json",
        data: {
            productExchangeApprovalId:baseInfo.productExchangeApprovalId
        },
        success: (function (data) {
            if (data.code == '000000') {
                var approvalResult = data.data;
                if(approvalResult.approvalStatus=='0'||approvalResult.approvalStatus=='2'){
                    $("#productRemarks").text(approvalResult.approvalRemarks).attr('readonly','readonly');
                    $('#productApprovalForm input').attr('disabled','disabled');
                    $('#productApprovalForm input[value="'+approvalResult.approvalStatus+'"]').attr('checked','checked');
                    $("#productExchangeBtn").hide();
                }
            }
        }),
        error: (function () {
            $.alert(
                {
                    'title':'提示',
                    'content':"获取信息失败"
                }
            );
        })
    })

}
$("#contractNumber").click(function(){
    contractNumberDetail(baseInfo.contractId)
})

function  contractNumberDetail(contractId) {
    if(contractId == null || contractId == '') {
        $.alert(
            {
                'title':'提示',
                'content':"合同信息有误!"
            }
        );
        return;
    }
    parent.$(parent.document).data('multitabs').create({
        iframe : true,
        title : '合同详情',
        url : "/front/contractManager/contractDetail?contractId=" + contractId
    }, true);
}
function productApprovalValidator(){
    $('#productApprovalForm').bootstrapValidator({
        fields: {
            productRemarks: {
                validators: {
                    notEmpty: {
                        message: '备注不能为空'
                    }
                }
            },
            productApprovalResult:{
                validators: {
                    notEmpty: {
                        message: '审批结果不能为空'
                    }
                }
            }
        }
    })
}
$(function () {
    baseInfoAssignment(baseInfo)
    productApprovalValidator()
    tableList('productDetail','/csd/productManager/selectProductExchangeApprovalByExchangeNumber',productColumns,productParams);
    tableList('exchangeProductDetail','/csd/productManager/selectProductExchangeApprovalByExchangeNumber',exchangedProductColumns,exchangeProductParams)
})
let productParams=function(params){
    params.exchangeNumber=baseInfo.exchangeNumber;
    params.type='1';
    return params;
}
let exchangeProductParams=function(params){
    params.exchangeNumber=baseInfo.exchangeNumber;
    params.type='';
    return params;
}
let productColumns=[
    {title: '序号', field: 'index', align: 'center', valign: 'left', formatter: indexFormat},
    {title: '产品名称',field: 'exchangeProductName', align: 'left', valign: 'middle'},
    {title: '产品号',field: 'finishOrderProductNum', align: 'left', valign: 'middle'},
    {title: '产品成交价',field: 'productFinalPrice', align: 'left', valign: 'middle'},
    {title: '使用状态',field: 'operater', align: 'left', valign: 'middle'},
]
let exchangedProductColumns=[
    {title: '序号', field: 'index', align: 'center', valign: 'left', formatter: indexFormat},
    {title: '产品名称',field: 'productName', align: 'left', valign: 'middle'},
    {title: '产品原价',field: 'productOriginalPrice', align: 'left', valign: 'middle',formatter:function(value){
            if(!value&&value!==0){
                return '-'
            }else{
                return value
            }
        }},
    {title: '产品单价',field: 'productUnitPrice', align: 'left', valign: 'middle',formatter:function(value){
            if(!value&&value!==0){
                 return '-'
            }else{
                return value
            }
        }},
    {title: '产品会员价',field: 'productMemberPrice', align: 'left', valign: 'middle',formatter:function(value){
            if(!value&&value!==0){
                return '-'
            }else{
                return value
            }
        }},
    {title: '会员售价价格',field: 'sellingCardPrice', align: 'left', valign: 'middle',formatter:function(value){
            if(!value&&value!==0){
                return '-'
            }else{
                return value
            }
        }},
    {title: '定价价格',field: 'price', align: 'left', valign: 'middle',formatter:function(value){
            if(!value&&value!==0){
                return '-'
            }else{
                return value
            }
        }}
]
/**
 * --列表序列号
 */
function indexFormat(value, row, index) {
    return index + 1;
}
function tableList(domId,url,columns,queryParams) {
    $(`#${domId}`).bootstrapTable('destroy');
    $(`#${domId}`).bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: url,
        method: 'get',                                      // 请求方式
        contentType: 'application/x-www-form-urlencoded',   // 请求内容类型
        dataType: 'json',                                   // 数据类型
        striped: true,                                      // 是否显示行间隔色
        sortable: true,                                     // 是否启用排序
        sortOrder: 'desc',                                  // 排序方式
        sortName: 'createTm',                               // 排序字段
        cache: false,                                       // 是否使用缓存
        showColumns: false,                                 // 显示隐藏列
        showRefresh: false,                                 // 显示刷新按钮
        showToggle: false,                                  // 切换显示样式
        showFooter: false,                                  // 显示Table脚部
        pagination: true,                                   // 是否显示分页
        showPaginationSwitch: false,                        // 是否显示分页按钮
        clickToSelect: true,                                // 是否启用点击选中行
        maintainSelected: true,                             // 分页是否保留选中
        singleSelect: false,
        undefinedText: '-',                                 // cell没有值时显示
        sidePagination: 'client',                           // 分页方式：client客户端分页，server服务端分页
        pageSize: 10,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: [10,15,20],//可供选择的每页的行数
        queryParams: queryParams,  // 查询参数
        columns: columns,
        responseHandler: function (result) {
            if (result.code == "000000") {
                    var obj = {
                        "rows": result.data,
                        "total": result.totalRecords//总条数
                    };
                    if(domId=='productDetail'){
                        productData=result.data
                    }

            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
                if(domId=='productDetail'){
                    productData=[]
                }
            }
            return obj;
        },
        onLoadSuccess: function (data) {
            // console.log(data)
        },
        onLoadError: function (status) {
            if (status == 403) {
                $.alert(
                    {
                        'title':'提示',
                        'content':"权限不足！禁止访问！"
                    }
                );
            } else {
                //加载失败时执行
                $.alert(
                    {
                        'title':'提示',
                        'content':"加载失败！"
                    }
                );
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });

}
//数组转字符串
function getDataStr(data,fileName){
    let arr=[];
    data.filter((item)=>{
        arr.push(item[fileName])
    })
    return arr.join()

}
function submitExamine(){
    var bootstrapValidator = $("#productApprovalForm").data('bootstrapValidator');
    bootstrapValidator.validate();
    if (!bootstrapValidator.isValid()) {
        return;
    }
    $.ajax({
        url: '/csd/productManager/updateProductExchangeApproval',
        type: 'POST',
        dataType: "json",
        data: {
            productExchangeApprovalId:baseInfo.productExchangeApprovalId,
            approvalStatus:$("input[name='productApprovalResult']:checked").val(),
            approvalRemarks:$.trim($("#productRemarks").val()),
            exchangeFinishOrderProductId:getDataStr(productData,'exchangeFinishOrderProductId'),
            exchangeNumber:baseInfo.exchangeNumber
        },
        success: (function (data) {
            if (data.code == '000000') {
                $.alert(
                    {
                        'title':'提示',
                        'content':"提交成功"
                    }
                );
                $("#productRemarks").attr('readonly','readonly');
                $('#productApprovalForm input').attr('disabled','disabled');
                $("#productExchangeBtn").hide();
                //清除校验
                $('#productApprovalForm').data('bootstrapValidator')?$('#productApprovalForm').data('bootstrapValidator').destroy():'';//清除校验
                productApprovalValidator()
            }
        }),
        error: (function () {
            $.alert(
                {
                    'title':'提示',
                    'content':"请求失败"
                }
            );
        })
    })


}
function cancel(){
    $("#productRemarks").val('').removeAttr('readonly');
    $('#productApprovalForm input').attr("checked", false).removeAttr("disabled");
    var bootstrapValidator = $("#productApprovalForm").data('bootstrapValidator');
    if (bootstrapValidator) {
        $("#productApprovalForm").data('bootstrapValidator').destroy();
        $('#productApprovalForm').data('bootstrapValidator', null);
    }
    $("#orderNumber").val("");
    productApprovalFormValidator();
}